package com.lucene.controller;

import com.alibaba.fastjson.JSONObject;
import com.lucene.model.Page;
import com.lucene.model.Project;
import com.lucene.service.LuceneService;
import com.lucene.service.ProjectService;
import com.lucene.utils.PageUtil;
import com.lucene.utils.Utils;
import org.apache.log4j.Logger;
import org.json.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Timestamp;
import java.util.List;

/**
 * Created by zhangzhen on 22/09/2017.
 */

@RestController
@RequestMapping(value = "/project")
public class ProjectController {
    private static Logger logger = Logger.getLogger(ProjectController.class);

    @Autowired
    private ProjectService projectService;

    @Autowired
    private LuceneService luceneService;

    @RequestMapping(value = "/")
    public ModelAndView addProjectPage(){
        return new ModelAndView("index");
    }


    @RequestMapping(value="/addProject")
    public @ResponseBody
    String addProject(@RequestBody Project project){

        JSONObject object = new JSONObject();

        logger.info(project);
        try {
            Project p = projectService.searchProjectByKey(project);
            if (p!=null){
                object.put("code","1");
                object.put("msg","key值已经存在.");
            }else {
                project.setCreate_time(new Timestamp(System.currentTimeMillis()));//创建时间
                project.setUpdate_time(new Timestamp(System.currentTimeMillis()));//更新时间
                int rs = projectService.addProject(project);
                if ( rs > 0 ){
                    //更新索引
                    luceneService.addOneItemIndex(project);
                    logger.info("添加新索引....");
                    object.put("code","0");
                    object.put("msg","添加成功.");
                }else {
                    object.put("code","1");
                    object.put("msg","添加失败.");
                }
            }
        }catch (Exception e){
            object.put("code","2");
            object.put("msg","网络异常.");
        }
        return object.toJSONString();
    }

    @RequestMapping(value = "/search")
    public ModelAndView searchProjectPage(){
        return new ModelAndView("project/search");
    }

    @RequestMapping(value = "/search.do")
    public @ResponseBody
    String searchProjects(@RequestParam(value = "queryStr") String queryStr){
        JSONObject object = new JSONObject();
        List<Project> projects = luceneService.searchProject(queryStr);
        object.put("projects",projects);
        return object.toJSONString();
    }

    @RequestMapping(value = "/add")
    public ModelAndView addProjectView(){
        return new ModelAndView("project/addProject");
    }

    @RequestMapping(value = "/detail")
    public ModelAndView detailProject(@RequestParam(value = "pid") Integer pid){
        ModelAndView mv = new ModelAndView("project/detailProject");
        Project p = new Project();
        p.setId(pid);
        Project project = projectService.queryProjectById(p);
        mv.addObject("project", project);
        return mv;
    }

    @RequestMapping(value = "/edit")
    public ModelAndView editProject(@RequestParam(value = "pid") Integer pid){
        ModelAndView mv = new ModelAndView("project/editProject");
        Project p = new Project();
        p.setId(pid);
        Project project = projectService.queryProjectById(p);
        mv.addObject("project", project);
        return mv;
    }

    @RequestMapping(value="/update")
    public @ResponseBody
    String updateProject(@RequestBody Project project){

        JSONObject object = new JSONObject();

        logger.info(project);
        try {
            Project p = projectService.searchProjectByKey(project);
            // exists the entity and dont shares the id.
            if (p!=null && p.getId()!=project.getId()){
                object.put("code","1");
                object.put("msg","key值已经存在.");
            }else {
                project.setUpdate_time(new Timestamp(System.currentTimeMillis()));//更新时间
                int rs = projectService.updateProject(project);
                if ( rs > 0 ){
                    //更新索引
                    luceneService.addOneItemIndex(project);
                    logger.info("更新新索引....");
                    object.put("code","0");
                    object.put("msg","更新数据成功.");
                }else {
                    object.put("code","1");
                    object.put("msg","更新数据失败.");
                }
            }
        }catch (Exception e){
            object.put("code","2");
            object.put("msg","网络异常.");
        }
        return object.toJSONString();
    }

    @RequestMapping(value = "/del")
    public @ResponseBody
    String delProject(@RequestParam(value = "pid") Integer pid){
        logger.info("del the pid=" + pid);
        JSONObject object = new JSONObject();
        try {
            Project project = new Project();
            project.setId(pid);

            int rs = projectService.delProject(project);
            if (rs>0){
                object.put("code","0");
                object.put("msg","删除成功.");
            }else {
                object.put("code","1");
                object.put("msg","无对应项.");
            }
        }catch (Exception e){
            object.put("code","2");
            object.put("msg","操作异常.");
        }
        return object.toJSONString();
    }

    @RequestMapping(value = "/show")
    public ModelAndView showProjectPage(){
        return new ModelAndView("project/listProjects");
    }

    /**
     * get projects by pagination.
     * @return
     */
    @RequestMapping(value = "/query")
    public @ResponseBody
    String queryProject(@RequestParam(value = "page") Integer pageNum,
                        @RequestParam(value = "limit") Integer limit,
                        @RequestParam(value = "key[search]",required = false, defaultValue = "") String search){
        logger.info("query the page=" + pageNum +", limit=" + limit+" , search=" + search);
        JSONObject object = new JSONObject();
        try {
            int total = projectService.queryProjectsNum(search);
            Page page = PageUtil.createPage(limit,total,pageNum);
            page.setSearch(search);
            page.setSearch(search);
            List<Project> projects = projectService.queryProjectByPage(page);
            object.put("code", 0);
            object.put("count", total);
            object.put("data",projects);
        }catch (Exception e){
            object.put("code", 1);
            e.printStackTrace();
        }
        return object.toJSONString();
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///  问题组操作
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////


    @RequestMapping(value="/updateGroup")
    public @ResponseBody
    String updateProjectGroup(HttpServletRequest request){
        JSONObject object = new JSONObject();

        JSONObject paramJson = Utils.convert2Json(request);
        Project project = new Project(paramJson.getInteger("id"),
                paramJson.getInteger("flag"),
                paramJson.getString("descGroup"));
        logger.info(project);
        try {
            int rs = projectService.updateProjectGroup(project);
            if ( rs > 0 ){
                object.put("code","0");
                object.put("msg","更新问题组数据成功.");
            }else {
                object.put("code","1");
                object.put("msg","更新问题组数据失败.");
            }
        }catch (Exception e){
            object.put("code","2");
            object.put("msg","网络异常.");
        }
        return object.toJSONString();
    }
}
